# -*- coding: utf-8 -*-
import random, os, time

from selenium.common.exceptions import TimeoutException
from scrapy import signals
from fake_useragent import UserAgent
from scrapy.http import HtmlResponse
from selenium.webdriver.common.keys import Keys


class TaobaospiderSpiderMiddleware(object):
    """SpiderMiddleware"""
    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class RandomUserAgentDownloadMiddleware(object):
    """
    DownloadMiddleware: 通过fake-useragent第三方插件实现动态更换user-agent
    """
    def __init__(self, crawler):
        super(RandomUserAgentDownloadMiddleware, self).__init__()
        self.ua = UserAgent()
        self.ua_type = crawler.settings.get("RANDOM_USER_AGENT_TYPE", "random")

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider):
        def get_ua():
            return getattr(self.ua, self.ua_type) #ua.random
        user_agent = get_ua()
        #设置headers
        request.headers.setdefault('User-Agent', user_agent)


class RandomIpProxyDownloadMiddleware(object):
    """
    DownloadMiddleware: 动态代理iP
    """
    def process_request(self, request, spider):
        pass
        # request.meta["proxy"] = "http://36.25.34.0:808"


class DynamicLoadingHtmlDownloadMiddleware(object):
    """
    DownloadMiddleware: 拦截scrapy自带下载器的下载功能
        使用selenium内置的chrome浏览器动态加载html页面并返回给spider
    """
    def process_request(self, request, spider):
        if spider.name == "taobao_jiaju":
            if request.url[-4:] not in [".jpg", ".png", "bmp", "gif"]:
                """下载网页"""
                try:
                    spider.browser.get(request.url)
                    if request.url != "https://www.taobao.com/":
                        # for i in range(0, 150):
                        #     spider.browser.find_element_by_xpath('/html/body').send_keys(Keys.DOWN)
                        for i in range(100, 1050, 50):
                            spider.browser.execute_script('window.scrollBy(0,{0});'.format(i))
                            spider.browser.implicitly_wait(1)
                except TimeoutException as e:
                    spider.browser.execute_script('window.stop()')
                return HtmlResponse(url=spider.browser.current_url,body=spider.browser.page_source,encoding="utf-8",request=request)
            else:
                """
                下载图片,什么都不写使用默认下载器,也可以使用selenium下载器
                """
                pass
